package org.apache.zookeeper.client.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.data.Stat;

/**
 * <h2>curator客户端</h2>
 * description:
 *
 * @author yongjun.ji(yongjun.ji @ ucarinc.com)
 * @since 1.0 2020/6/15 11:16
 */
public class CuratorClientTest {

    public static void main(String[] args) throws Exception {
        String path = "/testCurator";
        CuratorFramework cli = CuratorFrameworkFactory.newClient("localhost:2181", 1000, 100, new RetryNTimes(1, 100));
        cli.start();

        // 监听连接状态
        cli.getConnectionStateListenable().addListener(new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                System.out.println("新状态：" + newState);
                System.out.println(client == cli);
                System.out.println(client.equals(cli));

                if (newState == ConnectionState.LOST) {
                    try {
                        client.blockUntilConnected();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread.sleep(2000);
        System.out.println("sleep结束");

        Stat stat = cli.checkExists().forPath(path);
        if (stat == null) {
            String result = cli.create().forPath(path, "测试curator客户端".getBytes());
            System.out.println(result);
        }

        CuratorCache curatorCache = CuratorCache.build(cli, path);
        curatorCache.start();

        // 缓存节点数据，监听set动作
        curatorCache.listenable().addListener(new CuratorCacheListener() {
            @Override
            public void event(Type type, ChildData oldData, ChildData data) {
                System.out.println("类型：" + type + ",旧数据：" + new String(oldData.getData()) + "，\n新数据：" + new String(data.getData()));
            }
        });

        // 类似于原生的getData(path, watcher)
        cli.getData().usingWatcher(new CuratorWatcher() {
            @Override
            public void process(WatchedEvent event) throws Exception {
                System.out.println("getData监听：" + event);
            }
        }).forPath(path);

        System.out.println("ready!");

        System.in.read();
    }
}
